package Action.BackgroundThread;

import Action.Sys.Setting;
import Bean.Log.SystemLogEntity;
import org.hibernate.Session;
import tools.HibernateTools;
import tools.TimeTools;

import java.util.HashSet;

public final class GcThread extends Thread{
    private static GcThread gcThread=new GcThread();
    Session session;
    //磁盘定时缓存清理线程
       @Override
       public void run() {
           super.run();
           try {
               sleep(10000);//注意此处需要推迟,否则项目启动将会缓慢
           } catch (InterruptedException e) {
           }
           long time=Setting.SYS_min_cache_time*1000*60;//检测周期
           long middle=System.currentTimeMillis();
           while (true) {
               try {
                   sleep(time+5000);
               } catch (InterruptedException e) {
               }
               session=HibernateTools.getSession();
               if (System.currentTimeMillis()-middle>Setting.SYS_min_cache_time*60*1000){
                   //由于时间触发存储检查
                   System.out.println(TimeTools.timeStamp2Date(null,null)+"缓存定时清理:");
                   Setting.clear_cache();
                   middle=System.currentTimeMillis();
               }
               if (Setting.cache_size()> Setting.SYS_cache_MaxSize*1024){
                   System.err.println(TimeTools.timeStamp2Date(null,null)+"当前缓存:"+Setting.cache_size()/1024+"MB超过预定大小"+Setting.SYS_cache_MaxSize+"MB,如果频繁出现请适当扩大磁盘缓存空间");
                   Setting.clear_cache();
               }
               HibernateTools.commit(session);
           }
       }
    //禁止主动初始化并拿到对象
    private GcThread(){

    }

    //单例--懒汉模式
    public static synchronized GcThread getInstance() {
        return gcThread;
    }


    public  boolean StartGc(){
        if (!gcThread.isAlive())
        synchronized (this) {
            if (gcThread.isAlive()) {//二次验证
                return true;
            }
            try {
                gcThread=new GcThread();//原来线程已经失效
                gcThread.setName("图书借阅系统的GC---高金磊");
                gcThread.setPriority(3);
                gcThread.start();
                System.err.println(TimeTools.timeStamp2Date(null, null)+"缓存清理线程已经启动");
            } catch (Exception e) {
                System.out.println(TimeTools.timeStamp2Date(null, null)+"GC线程没有正常启动");
                session = HibernateTools.getSession();
                SystemLogEntity.addLog(-1, null, "GC线程没有正常启动"+e.getCause());
                HibernateTools.commit(session);
                e.printStackTrace();
                return false;
            }
        }
        System.err.println(TimeTools.timeStamp2Date(null, null)+"缓存清理线程正常运行");
        return true;
    }

}
